<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <h1>成本看板</h1>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-refresh" @click="refreshData">刷新数据</el-button>
      </div>
    </div>

    <!-- 顶部统计卡片 -->
    <div class="metrics-grid">
      <!-- 工时成本卡片 -->
      <div class="metric-card">
        <div class="metric-title">工时成本</div>
        <div class="metric-value">¥{{ formatNumber(totalLaborCost) }}</div>
        <div class="metric-desc">{{ laborProjectCount }}个项目</div>
      </div>

      <!-- 报销成本卡片 -->
      <div class="metric-card">
        <div class="metric-title">报销成本</div>
        <div class="metric-value">¥{{ formatNumber(totalReimbursementCost) }}</div>
        <div class="metric-desc">{{ reimbursementProjectCount }}个项目</div>
      </div>

      <!-- 付款成本卡片 -->
      <div class="metric-card">
        <div class="metric-title">付款成本</div>
        <div class="metric-value">¥{{ formatNumber(totalPaymentCost) }}</div>
        <div class="metric-desc">{{ paymentProjectCount }}个项目</div>
      </div>

      <!-- 总成本卡片 -->
      <div class="metric-card">
        <div class="metric-title">总成本</div>
        <div class="metric-value">¥{{ formatNumber(totalCost) }}</div>
        <div class="metric-desc">{{ totalProjectCount }}个项目</div>
      </div>
    </div>

    <!-- 成本统计标签页 -->
    <div class="cost-tabs">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">

        <!-- 工时成本统计 -->
        <el-tab-pane label="工时成本统计" name="labor">
          <div class="tab-content">
            <div class="stats-summary">
              <div class="summary-item">
                <span class="summary-label">项目总数</span>
                <span class="summary-value">{{ laborProjectCount }}</span>
              </div>
              <div class="summary-item">
                <span class="summary-label">总工时成本</span>
                <span class="summary-value">¥{{ formatNumber(totalLaborCost) }}</span>
              </div>
            </div>

            <div class="table-container">
              <el-table
                :data="laborStats"
                style="width: 100%"
                v-loading="laborLoading"
                class="centered-table"
              >
                <el-table-column prop="projectName" label="项目名称" align="center"></el-table-column>
                <el-table-column prop="totalLaborCost" label="工时成本" align="center">
                  <template #default="{ row }">
                    ¥{{ formatNumber(row.totalLaborCost) }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>

        <!-- 报销成本统计 -->
        <el-tab-pane label="报销成本统计" name="reimbursement">
          <div class="tab-content">
            <div class="stats-summary">
              <div class="summary-item">
                <span class="summary-label">项目总数</span>
                <span class="summary-value">{{ reimbursementProjectCount }}</span>
              </div>
              <div class="summary-item">
                <span class="summary-label">总报销成本</span>
                <span class="summary-value">¥{{ formatNumber(totalReimbursementCost) }}</span>
              </div>
            </div>

            <div class="table-container">
              <el-table
                :data="reimbursementStats"
                style="width: 100%"
                v-loading="reimbursementLoading"
                class="centered-table"
              >
                <el-table-column prop="projectName" label="项目名称" align="center"></el-table-column>
                <el-table-column prop="totalAmount" label="报销成本" align="center">
                  <template #default="{ row }">
                    ¥{{ formatNumber(row.totalAmount) }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>

        <!-- 付款成本统计 -->
        <el-tab-pane label="付款成本统计" name="payment">
          <div class="tab-content">
            <div class="stats-summary">
              <div class="summary-item">
                <span class="summary-label">项目总数</span>
                <span class="summary-value">{{ paymentProjectCount }}</span>
              </div>
              <div class="summary-item">
                <span class="summary-label">总付款成本</span>
                <span class="summary-value">¥{{ formatNumber(totalPaymentCost) }}</span>
              </div>
            </div>

            <div class="table-container">
              <el-table
                :data="paymentStats"
                style="width: 100%"
                v-loading="paymentLoading"
                class="centered-table"
              >
                <el-table-column prop="projectName" label="项目名称" align="center"></el-table-column>
                <el-table-column prop="totalAmount" label="付款成本" align="center">
                  <template #default="{ row }">
                    ¥{{ formatNumber(row.totalAmount) }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>

        <!-- 项目总成本统计 - 放在最后面 -->
        <el-tab-pane label="项目总成本" name="total">
          <div class="tab-content">
            <div class="stats-summary">
              <div class="summary-item">
                <span class="summary-label">有成本项目数</span>
                <span class="summary-value">{{ totalProjectCount }}</span>
              </div>
              <div class="summary-item">
                <span class="summary-label">总成本</span>
                <span class="summary-value">¥{{ formatNumber(totalCost) }}</span>
              </div>
            </div>

            <div class="table-container">
              <el-table
                :data="projectTotalStats"
                style="width: 100%"
                v-loading="totalLoading"
                class="centered-table">
                <el-table-column prop="projectName" label="项目名称" align="center" width="200"></el-table-column>
                <el-table-column prop="laborCost" label="工时成本" align="center">
                  <template #default="{ row }">
                    ¥{{ formatNumber(row.laborCost) }}
                  </template>
                </el-table-column>
                <el-table-column prop="reimbursementCost" label="报销成本" align="center">
                  <template #default="{ row }">
                    ¥{{ formatNumber(row.reimbursementCost) }}
                  </template>
                </el-table-column>
                <el-table-column prop="paymentCost" label="付款成本" align="center">
                  <template #default="{ row }">
                    ¥{{ formatNumber(row.paymentCost) }}
                  </template>
                </el-table-column>
                <el-table-column prop="totalCost" label="项目总成本" align="center">
                  <template #default="{ row }">
                    <span style="font-weight: bold; color: #409EFF;">
                      ¥{{ formatNumber(row.totalCost) }}
                    </span>
                  </template>
                </el-table-column>
                <!-- 项目总收入列 -->
                <el-table-column prop="revenue" label="项目总收入" align="center">
                  <template #default="{ row }">
                    <span style="color: #67C23A;">
                      ¥{{ formatNumber(row.revenue) }}
                    </span>
                  </template>
                </el-table-column>
                <!-- 成本占比列 -->
                <el-table-column prop="costRate" label="成本占比" align="center">
                  <template #default="{ row }">
                    <span :style="{
                      color: row.costRate > 0.65 ? '#F56C6C' : row.costRate > 0.35 ? '#E6A23C' : '#67C23A',
                      fontWeight: 'bold'
                    }">
                      {{ formatPercentage(row.costRate) }}
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>

      </el-tabs>
    </div>
  </div>
</template>

<script>
import * as costApi from '@/api/cost/cost'

export default {
  name: 'CostDashboard',
  data() {
    return {
      // 激活的标签页
      activeTab: 'labor',

      // 成本汇总数据
      totalLaborCost: 0,
      totalReimbursementCost: 0,
      totalPaymentCost: 0,
      totalCost: 0,

      // 新增：总收入数据
      totalRevenue: 0,
      averageCostRate: 0,

      // 项目数量
      laborProjectCount: 0,
      reimbursementProjectCount: 0,
      paymentProjectCount: 0,

      // 统计详情数据
      laborStats: [],
      reimbursementStats: [],
      paymentStats: [],

      // 新增：项目收入数据
      projectRevenues: [],

      // 加载状态
      laborLoading: false,
      reimbursementLoading: false,
      paymentLoading: false,
      totalLoading: false
    }
  },

  computed: {
    // 计算项目总成本统计
    projectTotalStats() {
      const projectMap = new Map()

      // 合并工时成本数据
      this.laborStats.forEach(item => {
        const projectName = item.projectName
        if (!projectMap.has(projectName)) {
          projectMap.set(projectName, {
            projectName,
            laborCost: 0,
            reimbursementCost: 0,
            paymentCost: 0,
            totalCost: 0,
            revenue: 0,
            costRate: 0
          })
        }
        projectMap.get(projectName).laborCost = item.totalLaborCost || 0
      })

      // 合并报销成本数据
      this.reimbursementStats.forEach(item => {
        const projectName = item.projectName
        if (!projectMap.has(projectName)) {
          projectMap.set(projectName, {
            projectName,
            laborCost: 0,
            reimbursementCost: 0,
            paymentCost: 0,
            totalCost: 0,
            revenue: 0,
            costRate: 0
          })
        }
        projectMap.get(projectName).reimbursementCost = item.totalAmount || 0
      })

      // 合并付款成本数据
      this.paymentStats.forEach(item => {
        const projectName = item.projectName
        if (!projectMap.has(projectName)) {
          projectMap.set(projectName, {
            projectName,
            laborCost: 0,
            reimbursementCost: 0,
            paymentCost: 0,
            totalCost: 0,
            revenue: 0,
            costRate: 0
          })
        }
        projectMap.get(projectName).paymentCost = item.totalAmount || 0
      })

      // 合并项目收入数据
      this.projectRevenues.forEach(item => {
        const projectName = item.projectName
        if (projectMap.has(projectName)) {
          projectMap.get(projectName).revenue = item.revenue || 0
        }
      })

      // 计算每个项目的总成本和成本占比，并过滤出有成本的项目
      const result = Array.from(projectMap.values())
        .map(project => {
          project.totalCost = (project.laborCost || 0) + (project.reimbursementCost || 0) + (project.paymentCost || 0)
          // 计算成本占比，避免除零
          project.costRate = project.revenue > 0 ? project.totalCost / project.revenue : 0
          return project
        })
        .filter(project => project.totalCost > 0) // 只显示有成本的项目

      // 按总成本降序排序
      return result.sort((a, b) => b.totalCost - a.totalCost)
    },

    // 计算总项目数量（去重）- 修改为只计算有成本的项目
    totalProjectCount() {
      return this.projectTotalStats.length
    }
  },

  mounted() {
    this.initData()
  },

  methods: {
    // 初始化数据
    async initData() {
      this.totalLoading = true
      await Promise.all([
        this.loadLaborStats(),
        this.loadReimbursementStats(),
        this.loadPaymentStats(),
        this.loadProjectRevenues()
      ])
      this.calculateTotalCost()
      this.calculateAverageCostRate()
      this.totalLoading = false
    },

    // 计算总成本
    calculateTotalCost() {
      this.totalCost = this.totalLaborCost + this.totalReimbursementCost + this.totalPaymentCost
    },

    // 计算平均成本占比
    calculateAverageCostRate() {
      this.averageCostRate = this.totalRevenue > 0 ? this.totalCost / this.totalRevenue : 0
    },

    // 新增：加载项目收入数据
    async loadProjectRevenues() {
      try {
        const response = await costApi.getProjectRevenues()
        if (response.code === 200) {
          this.projectRevenues = response.data || []
          // 计算总收入
          this.totalRevenue = this.projectRevenues.reduce((sum, item) => sum + (item.revenue || 0), 0)
        } else {
          this.$message.error(response.message || '加载项目收入数据失败')
        }
      } catch (error) {
        console.error('加载项目收入数据失败:', error)
        this.$message.error('加载项目收入数据失败')
      }
    },

    // 加载工时成本统计
    async loadLaborStats() {
      this.laborLoading = true
      try {
        const response = await costApi.getLaborStatistics()
        if (response.code === 200) {
          this.laborStats = response.data?.projectCostList || []
          this.laborProjectCount = response.data?.projectCount || 0
          this.totalLaborCost = response.data?.totalCost || 0
        } else {
          this.$message.error(response.message || '加载工时成本统计失败')
        }
      } catch (error) {
        console.error('加载工时成本统计失败:', error)
        this.$message.error('加载工时成本统计失败')
      } finally {
        this.laborLoading = false
      }
    },

    // 加载报销成本统计
    async loadReimbursementStats() {
      this.reimbursementLoading = true
      try {
        const response = await costApi.getReimbursementStatistics()
        if (response.code === 200) {
          this.reimbursementStats = response.data?.projectCostList || []
          this.reimbursementProjectCount = response.data?.projectCount || 0
          this.totalReimbursementCost = response.data?.totalCost || 0
        } else {
          this.$message.error(response.message || '加载报销成本统计失败')
        }
      } catch (error) {
        console.error('加载报销成本统计失败:', error)
        this.$message.error('加载报销成本统计失败')
      } finally {
        this.reimbursementLoading = false
      }
    },

    // 加载付款成本统计
    async loadPaymentStats() {
      this.paymentLoading = true
      try {
        const response = await costApi.getPaymentStatistics()
        if (response.code === 200) {
          this.paymentStats = response.data?.projectCostList || []
          this.paymentProjectCount = response.data?.projectCount || 0
          this.totalPaymentCost = response.data?.totalCost || 0
        } else {
          this.$message.error(response.message || '加载付款成本统计失败')
        }
      } catch (error) {
        console.error('加载付款成本统计失败:', error)
        this.$message.error('加载付款成本统计失败')
      } finally {
        this.paymentLoading = false
      }
    },

    // 标签页切换
    handleTabClick(tab) {
      this.activeTab = tab.name
      if (tab.name === 'labor' && this.laborStats.length === 0) {
        this.loadLaborStats()
      } else if (tab.name === 'reimbursement' && this.reimbursementStats.length === 0) {
        this.loadReimbursementStats()
      } else if (tab.name === 'payment' && this.paymentStats.length === 0) {
        this.loadPaymentStats()
      }
    },

    // 刷新数据
    refreshData() {
      this.totalLoading = true
      Promise.all([
        this.loadLaborStats(),
        this.loadReimbursementStats(),
        this.loadPaymentStats(),
        this.loadProjectRevenues()
      ]).then(() => {
        this.calculateTotalCost()
        this.calculateAverageCostRate()
        this.totalLoading = false
        this.$message.success('数据已刷新')
      })
    },

    // 格式化数字
    formatNumber(num) {
      if (!num) return '0'
      return Number(num).toLocaleString()
    },

    // 新增：格式化百分比
    formatPercentage(rate) {
      if (!rate) return '0%'
      return (rate * 100).toFixed(2) + '%'
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 24px;
  background: #ffffff;
  min-height: calc(100vh - 84px);
}

.dashboard-header {
  margin-bottom: 32px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  h1 {
    font-size: 32px;
    font-weight: 600;
    color: #1a1a1a;
    margin: 0;
  }

  .header-actions {
    display: flex;
    gap: 12px;
    align-items: center;
  }
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24px;
  margin-bottom: 32px;
}

.metric-card {
  background: #ffffff;
  padding: 32px 24px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  text-align: center;
  transition: all 0.2s ease;

  &:hover {
    border-color: #d1d5db;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  }

  .metric-title {
    font-size: 14px;
    color: #6b7280;
    margin-bottom: 12px;
    font-weight: 500;
  }

  .metric-value {
    font-size: 28px;
    font-weight: 700;
    color: #111827;
    margin-bottom: 8px;
  }

  .metric-desc {
    font-size: 12px;
    color: #9ca3af;
  }
}

.cost-tabs {
  .el-tabs__content {
    padding-top: 24px;
  }
}

.tab-content {
  display: flex;
  flex-direction: column;
  align-items: center;

  .stats-summary {
    display: flex;
    gap: 32px;
    margin-bottom: 24px;
    padding: 20px;
    background: #f9fafb;
    border-radius: 8px;
    width: 100%;
    max-width: 800px;
    justify-content: center;

    .summary-item {
      display: flex;
      flex-direction: column;
      align-items: center;

      .summary-label {
        font-size: 14px;
        color: #6b7280;
        margin-bottom: 8px;
      }

      .summary-value {
        font-size: 20px;
        font-weight: 700;
        color: #111827;
      }
    }
  }

  .table-container {
    width: 95%;
    max-width: 1200px;
    margin: 0 auto;

    .centered-table {
      .el-table__header-wrapper,
      .el-table__body-wrapper {
        th,
        td {
          text-align: center;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .metrics-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .dashboard-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;

    .header-actions {
      width: 100%;
      justify-content: space-between;
    }
  }

  .stats-summary {
    flex-direction: column;
    gap: 16px !important;
  }

  .tab-content {
    .table-container {
      width: 100%;
      max-width: 100%;
    }
  }
}
</style>
